<?php

namespace JsonLowCode\Support;

use JsonLowCode\JsBase;

/**
 * JsRouter 路由类
 * @method static JsRouter make(bool $isFunction = true)
 */
class JsRouter extends JsBase
{
    protected string $router = "this.\$router";

    /**
     * @param bool $isFunction 是否函数包裹
     */
    public function __construct(bool $isFunction = true){
        $this->router = Js::router();
        $this->setJsFunction($isFunction);
    }

    /**
     * 返回首页
     * @param bool $newTab 是否新标签打开
     * @return string
     */
    public function toHome(bool $newTab = false): string
    {
        $this->script = Js::tools().".toHome({$newTab});";
        return $this->toString();
    }

    /**
     * 返回上一级路由
     * @return string
     */
    public function back(): string
    {
        $this->script = "{$this->router}?.back();";
        return $this->toString();
    }

    /**
     * 前进一级路由
     * @return string
     */
    public function forward(): string
    {
        $this->script = "{$this->router}?.forward();";
        return $this->toString();
    }

    /**
     * 跳转路由
     * @param string|array $to
     * @param bool $newTab 是否新标签打开
     * @return string
     */
    public function push(string|array $to, bool $newTab = false): string
    {
        $to = $this->jsFrom($to);
        $this->script = Js::tools().".routerPush({$to},{$newTab});";
        return $this->toString();
    }

    /**
     * 替换路由
     * @param string|array $to
     * @return string
     */
    public function replace(string|array $to): string
    {
        $to = $this->jsFrom($to);
        $this->script = "{$this->router}?.replace({$to});";
        return $this->toString();
    }

    /**
     * 是否存在路由
     * @param string $name
     * @return string
     */
    public function hasRoute(string $name): string
    {
        $this->script = "{$this->router}?.hasRoute('{$name}')";
        return $this->toString();
    }

    /**
     * 获取所有路由
     * @return string
     */
    public function getRoutes(): string
    {
        $this->script = "{$this->router}?.getRoutes()";
        return $this->toString();
    }

    /**
     * 是否存在路由
     * @return string
     */
    public function currentRoute(): string
    {
        $this->script = "{$this->router}?.currentRoute";
        return $this->toString();
    }

}
